package cn.jy.ad.service.impl;

import cn.jy.ad.common.SnowFlake;
import cn.jy.ad.mapper.ExpressAppAdsMapper;
import cn.jy.ad.service.AppAdsService;
import cn.jy.common.ad.domain.ExpressAppAds;
import cn.jy.common.ad.domain.dto.ExpressAppAdsDto;
import cn.jy.common.ad.domain.vo.ExpressSplitAdvertisingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AppAdsServiceImpl implements AppAdsService {

    @Autowired
    private ExpressAppAdsMapper expressAppAdsMapper;

    @Override
    public List<ExpressAppAdsDto> list(ExpressSplitAdvertisingVo vo) {
        return expressAppAdsMapper.list(vo);
    }

    @Override
    public Integer count(ExpressSplitAdvertisingVo vo) {
        return expressAppAdsMapper.count(vo);
    }

    @Override
    public void updateStatus(ExpressAppAds expressAppAds) {
        expressAppAdsMapper.updateAppAds(expressAppAds);
    }

    @Override
    public void addAppAds(ExpressAppAds expressAppAds) {
        long sn = SnowFlake.nextId();
        expressAppAds.setSn(String.valueOf(sn));
        expressAppAdsMapper.addAppAds(expressAppAds);
    }


    private void updateAdStatus(ExpressAppAds ad) {
        try {
            ExpressAppAds expressAppAds = new ExpressAppAds();
            expressAppAds.setId(ad.getId());
            expressAppAds.setIsStatus(1); // 假设 1 表示广告已过期或停用
            expressAppAdsMapper.updateAppAds(expressAppAds);
            log.info("Updated ad status for ad ID: {}", ad.getId());
        } catch (Exception e) {
            log.error("Error updating ad status for ad ID {}: {}", ad.getId(), e.getMessage(), e);
        }
    }


    private void checkAndUpdateExpiredAds() {
        Date currentTime = new Date();
        List<ExpressAppAds> expiredAds = expressAppAdsMapper.selectExpiredAds(currentTime);
        expiredAds.forEach(this::updateAdStatus);
        log.info("Checked and updated statuses of expired ads.");
    }

    @Override
    public ExpressAppAds selectAppAdById(Integer id) {
        return expressAppAdsMapper.selectAppAdById(id);
    }

    @Override
    public void updateAppAds(ExpressAppAds expressAppAds) {
        expressAppAdsMapper.updateAppAds(        expressAppAds);
        log.info("Updated app ad with ID: {}", expressAppAds.getId());
    }

}
